﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Management;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.Management;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.Management
{
    /// <summary>
    /// 处理失访命令
    /// </summary>
    public class UpdateBasicCommandHandler : IRequestHandler<UpdateBasicCommand, APIResult<object>>
    {
        /// <summary>
        /// sqlSugar
        /// </summary>
        private readonly SqlSugarContext sqlSugar;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateBasicCommandHandler> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="sqlSugar">sqlSugar</param>
        /// <param name="mapper"></param>
        public UpdateBasicCommandHandler(SqlSugarContext sqlSugar, IMapper mapper, ILogger<UpdateBasicCommandHandler> logger)
        {
            this.sqlSugar = sqlSugar;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 修改失访
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<object>> Handle(UpdateBasicCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result=new APIResult<object>();
            try
            {
                var entity = sqlSugar.db.Queryable<Basic>().First(x => x.BasicId == request.BasicId);
                entity.UpName = request.UpName;
                entity.LossToFollowUpReason=request.LossToFollowUpReason;
                entity.Remarks=request.Remarks;
                entity.Status = "失访";
                entity.FollowUpTime=DateTime.Now;
                var i = sqlSugar.db.Updateable(entity).ExecuteCommand();
                if (i > 0)
                {
                    result.Code = APIEnum.修改成功;
                    result.Msg = APIEnum.修改成功.ToString();
                   result.data= i;
                }
                else
                {
                    result.Code = APIEnum.修改失败;
                    result.Msg = APIEnum.修改失败.ToString();
                }
               
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改失访时发生异常");
            }
            return Task.FromResult(result);
        }
    }
}
